package com.frxuexi.shop.view

import android.content.Context
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.frxuexi.lib_base.R
import com.frxuexi.lib_base.entity.CommentBean
import com.frxuexi.lib_base.entity.ShopDetailBean
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.RequestType
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.room.ShopEntity
import com.frxuexi.lib_base.utils.LiveDateBus
import com.frxuexi.shop.intent.ShopIntent
import com.frxuexi.shop.viewmodel.ShopViewModel
import com.frxuexi.shop.adapter.CommentAdapter
import com.frxuexi.shop.adapter.ShopAdapter
import com.frxuexi.shop.databinding.ActivityShopBinding
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.youth.banner.loader.ImageLoader
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus

@Route(path = "/shop/ShopActivity")
@AndroidEntryPoint
class ShopActivity : BaseActivity<ActivityShopBinding, ShopIntent, ShopViewModel>() {
    override val binding: ActivityShopBinding by lazy { ActivityShopBinding.inflate(layoutInflater) }
    override val vm: ShopViewModel by viewModels<ShopViewModel>()
    val shopAdapter by lazy { ShopAdapter() }
    val commentAdapter by lazy { CommentAdapter() }
    lateinit var detailBean:ShopDetailBean
    lateinit var shopEntity: ShopEntity
    @JvmField
    @Autowired
    var id:Int=-1

    var flag=false//非收藏

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        when(it.type){
                            RequestType.DEFAULT->{
                                detailBean = it.data as ShopDetailBean
                                Glide.with(this@ShopActivity).load(detailBean.productInfo.image).into(binding.shopdetailIv)
                                binding.shopdetailTitle.setText(detailBean.productInfo.storeName)
                                binding.shopdetailPrice.setText("￥${detailBean.productInfo.price}")
                            }
                            RequestType.UPDATE->{
                                ToastUtils.showLong("点赞成功")
                                binding.shopdetailLove.setImageResource(R.drawable.ic_action_love)
                                flag=true
                            }
                            RequestType.ITEM->{
                                shopEntity= it.data as ShopEntity
                                binding.shopdetailLove.setImageResource(R.drawable.ic_action_love)
                                flag=true

                            }
                            RequestType.DELETE->{
                                binding.shopdetailLove.setImageResource(R.drawable.ic_action_nolove)
                                flag=false
                            }
                            RequestType.LOVES->{
                                val entities = it.data as Collection<ShopEntity>
                                Log.i("lr",entities.toString())
                            }
                            RequestType.ADD->{
                                ToastUtils.showLong("添加购物车成功")
                                LiveDateBus.with("nav",String::class.java).postValue("3")
//                                EventBus.getDefault().post("3")
                                finish()
                            }
                            RequestType.COMMENT->{
                                val bean = it.data as CommentBean
                                commentAdapter.addData(bean.list)
                                commentAdapter.notifyDataSetChanged()
                            }

                            else -> {}
                        }

                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        ARouter.getInstance().inject(this)
        vm.sendIntent(ShopIntent.getShopDetail(id.toInt()))

        vm.sendIntent(ShopIntent.isLove(id))

        vm.sendIntent(ShopIntent.getLoves)
        val banner_imgs = listOf<String>(
            "http://10.161.9.80:8080/crmebimage/public/maintain/2021/12/25/7a6475bba07c47bb98e5db0e0d21c8ebq5sw2kijlc.jpg",
            "http://10.161.9.80:8080/crmebimage/public/maintain/2021/12/25/37382cca048b4011bdbacd3cbbe0814daw1o5x0tco.jpg",
            "http://10.161.9.80:8080/crmebimage/public/maintain/2021/12/25/fef1aee22a04466d93693f5791d44bfd2rsm469mcr.jpg"
        )
        binding.banner.apply {
            setImages(banner_imgs)
            setImageLoader(object : ImageLoader(){
                override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
//                    Glide.with(context!!).load(path.toString()).into(imageView!!)
                    BitmapUtils.getInstance(context!!).loadBitmap(path.toString(),
                        ViewGroup.LayoutParams.MATCH_PARENT,200){
                        imageView?.setImageBitmap(it)
                    }
                }
            })
            start()
        }

        binding.shopdetailLove.setOnClickListener {
            val entity = ShopEntity(
                null,
                detailBean.productInfo.id,
                detailBean.productInfo.storeName,
                detailBean.productInfo.image,
                detailBean.productInfo.price
            )
            if(flag){
                vm.sendIntent(ShopIntent.deleteLove(shopEntity))
            }else {
                vm.sendIntent(ShopIntent.addLove(entity))
            }
        }

        binding.shopdetailAdd.setOnClickListener {
            val map = mapOf<String, Any>(
                "cartNum" to 1,
                "productId" to id,
                "productAttrUnique" to detailBean.productAttr[0].id
            )
            vm.sendIntent(ShopIntent.addCart(map))
        }

        binding.shopdetailTab.apply {
            addTab(newTab().setText("详情"))
            addTab(newTab().setText("评论"))
            addOnTabSelectedListener(object :OnTabSelectedListener{
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    if(tab?.position==0){
                        binding.shopdetailIv.visibility=View.VISIBLE
                        binding.shopdetailCommentRv.visibility=View.GONE
                    }else{
                        binding.shopdetailIv.visibility=View.GONE
                        binding.shopdetailCommentRv.visibility=View.VISIBLE
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {
                }

                override fun onTabReselected(tab: TabLayout.Tab?) {
                }
            })

            getTabAt(0)?.view?.isSelected=true
        }

        binding.shopdetailCommentRv.apply {
            adapter=commentAdapter
            layoutManager=LinearLayoutManager(this@ShopActivity)
        }
        vm.sendIntent(ShopIntent.getComments(id,1))

    }

}